package com.gitee.genshin.analyse.data.db;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.log.Log;
import com.gitee.genshin.analyse.data.vo.GenshinData;

import java.sql.SQLException;
import java.util.List;

/**
 * @author hongda.li.dlmu@qq.com 2022/7/13 9:22
 */
public class DatabaseConnection {
    public static final String TABLE_NAME = "genshin_data";

    /**
     * 查询数量
     *
     * @param sql    sql
     * @param params 参数
     * @return 数量
     */
    public int count(String sql, Object... params) {
        try {
            Number number = Db.use(DatabaseSource.getDataSource()).queryNumber(sql, params);
            return number == null ? 0 : number.intValue();
        } catch (SQLException e) {
            Log.get().error("查询数据出现错误[{}][{}]", sql, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询记录
     *
     * @param sql    sql
     * @param params 参数
     * @return 查询结果
     */
    public List<Entity> find(String sql, Object... params) {
        try {
            return Db.use(DatabaseSource.getDataSource()).query(sql, params);
        } catch (SQLException e) {
            Log.get().error("查询数据出现错误[{}][{}]", sql, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 插入数据
     *
     * @param genshinData 祈愿记录
     */
    public void insert(GenshinData genshinData) {
        Entity entity = Entity.create(TABLE_NAME);
        entity.set("id", genshinData.getId());
        entity.set("uid", genshinData.getUid());
        entity.set("gacha_type", genshinData.getGacha_type());
        entity.set("item_id", genshinData.getItem_id());
        entity.set("count", genshinData.getCount());
        entity.set("time", genshinData.getTime());
        entity.set("name", genshinData.getName());
        entity.set("lang", genshinData.getLang());
        entity.set("item_type", genshinData.getItem_type());
        entity.set("rank_type", genshinData.getRank_type());
        try {
            Db.use(DatabaseSource.getDataSource()).insert(entity);
            Log.get().info("保存数据成功[{}][{}][{}]",genshinData.getId(), genshinData.getTime(), genshinData.getName());
        } catch (SQLException e) {
            Log.get().error("保存数据出现错误[{}][{}]", genshinData, e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
